// 后台服务脚本
class TranslationService {
  constructor() {
    this.currentAPI = 'bing'; // 默认使用Bing翻译
    this.apiKeys = {};
    this.loadSettings();
  }

  async loadSettings() {
    const result = await chrome.storage.sync.get(['currentAPI', 'apiKeys', 'autoTranslate']);
    if (!result.currentAPI) {
      await chrome.storage.sync.set({ currentAPI: 'bing' });
    }
    this.currentAPI = result.currentAPI || 'bing';
    this.apiKeys = result.apiKeys || {};
    this.autoTranslate = result.autoTranslate !== false; // 默认开启
  }

  async saveSettings() {
    await chrome.storage.sync.set({
      currentAPI: this.currentAPI,
      apiKeys: this.apiKeys,
      autoTranslate: this.autoTranslate
    });
  }

  async translate(text, fromLang = 'auto', toLang = 'zh') {
    try {
      switch (this.currentAPI) {
        case 'baidu':
          return await this.translateWithBaidu(text, fromLang, toLang);
        case 'chrome':
          return await this.translateWithChrome(text, fromLang, toLang);
        case 'tencent':
          return await this.translateWithTencent(text, fromLang, toLang);
        case 'google':
          return await this.translateWithGoogle(text, fromLang, toLang);
        case 'deepl':
          return await this.translateWithDeepL(text, fromLang, toLang);
        case 'bing':
          return await this.translateWithBing(text, fromLang, toLang);
        case 'youdao':
          return await this.translateWithYoudao(text, fromLang, toLang);
        default:
          throw new Error('不支持的翻译服务');
      }
    } catch (error) {
      console.error('翻译失败:', error);
      return { error: error.message };
    }
  }

  async translateWithBing(text, fromLang, toLang) {
    // 只支持单词查询
    const url = `https://www.bing.com/dict/search?q=${encodeURIComponent(text)}&cc=cn`;
    const response = await fetch(url);
    if (!response.ok) {
      throw new Error(`Bing词典网页请求失败: ${response.status}`);
    }
    const html = await response.text();
    // 提取主释义（qdef）
    let translatedText = '';
    try {
      const divMatch = html.match(/<div class="qdef"[\s\S]*?<ul>([\s\S]*?)<\/ul>/);
      if (divMatch && divMatch[1]) {
        // 提取每个li
        const lis = divMatch[1].match(/<li>([\s\S]*?)<\/li>/g);
        if (lis && lis.length > 0) {
          translatedText = lis.map(li => {
            // 去除HTML标签
            return li.replace(/<[^>]+>/g, '').replace(/\s+/g, ' ').trim();
          }).join('\n');
        }
      }
      if (!translatedText) {
        translatedText = '未找到释义';
      }
    } catch (e) {
      translatedText = '解析失败';
    }
    return {
      originalText: text,
      translatedText,
      fromLang: fromLang,
      toLang: toLang,
      service: 'bing'
    };
  }

  async translateWithGoogle(text, fromLang, toLang) {
    const key = this.apiKeys.google;
    if (!key) {
      throw new Error('请先配置Google翻译API密钥');
    }

    const endpoint = 'https://translation.googleapis.com/language/translate/v2';
    const params = new URLSearchParams({
      q: text,
      source: fromLang,
      target: toLang,
      key: key
    });

    const response = await fetch(`${endpoint}?${params}`);
    if (!response.ok) {
      throw new Error(`Google翻译API错误: ${response.status}`);
    }

    const data = await response.json();
    return {
      originalText: text,
      translatedText: data.data.translations[0].translatedText,
      fromLang: fromLang,
      toLang: toLang,
      service: 'google'
    };
  }

  async translateWithYoudao(text, fromLang, toLang) {
    // 使用有道词典API，无需API密钥
    const params = new URLSearchParams({
      num: '5',
      ver: '3.0',
      doctype: 'json',
      cache: 'false',
      le: fromLang === 'auto' ? 'en' : fromLang,
      q: text
    });

    try {
      const response = await fetch(`https://dict.youdao.com/suggest?${params}`, {
        method: 'GET',
        headers: {
          'Accept': 'application/json'
        }
      });
      
      if (!response.ok) {
        throw new Error(`有道词典API错误: ${response.status}`);
      }

      const data = await response.json();
      console.log('有道词典API响应:', data); // 调试日志
      
      // 解析有道词典返回的数据
      let translatedText = '';
      
      if (data && data.data && data.data.entries && data.data.entries.length > 0) {
        // 提取释义
        const entries = data.data.entries;
        const translations = [];
        
        entries.forEach(entry => {
          if (entry.explain) {
            translations.push(entry.explain);
          }
        });
        
        if (translations.length > 0) {
          translatedText = translations.join('; ');
        } else {
          translatedText = '未找到释义';
        }
      } else if (data && data.data && data.data.entries && data.data.entries.length === 0) {
        translatedText = '未找到释义';
      } else {
        console.error('有道词典API响应格式异常:', data);
        translatedText = '解析失败';
      }

      return {
        originalText: text,
        translatedText: translatedText,
        fromLang: fromLang,
        toLang: toLang,
        service: 'youdao'
      };
    } catch (error) {
      console.error('有道词典API请求失败:', error);
      throw new Error(`有道词典请求失败: ${error.message}`);
    }
  }

  async sha256(message) {
    const msgBuffer = new TextEncoder().encode(message);
    const hashBuffer = await crypto.subtle.digest('SHA-256', msgBuffer);
    const hashArray = Array.from(new Uint8Array(hashBuffer));
    const hashHex = hashArray.map(b => b.toString(16).padStart(2, '0')).join('');
    return hashHex;
  }

  async translateWithBaidu(text, fromLang, toLang) {
    const appId = this.apiKeys.baidu?.appId;
    const secretKey = this.apiKeys.baidu?.secretKey;
    
    if (!appId || !secretKey) {
      throw new Error('请先配置百度翻译API密钥');
    }

    const salt = Date.now();
    const sign = appId + text + salt + secretKey;
    const signStr = md5(sign);

    const params = new URLSearchParams({
      q: text,
      from: fromLang === 'auto' ? 'auto' : fromLang,
      to: toLang,
      appid: appId,
      salt: salt,
      sign: signStr
    });

    const response = await fetch(`https://fanyi-api.baidu.com/api/trans/vip/translate?${params}`);
    if (!response.ok) {
      throw new Error(`百度翻译API错误: ${response.status}`);
    }

    const data = await response.json();
    if (data.error_code) {
      throw new Error(`百度翻译错误: ${data.error_msg || data.error_code}`);
    }

    return {
      originalText: text,
      translatedText: data.trans_result[0].dst,
      fromLang: data.from || fromLang,
      toLang: toLang,
      service: 'baidu'
    };
  }

  async translateWithChrome(text, fromLang, toLang) {
    // 使用Chrome内置翻译API
    try {
      const response = await fetch(`https://translate.googleapis.com/translate_a/single?client=gtx&sl=${fromLang}&tl=${toLang}&dt=t&q=${encodeURIComponent(text)}`);
      
      if (!response.ok) {
        throw new Error(`Chrome翻译API错误: ${response.status}`);
      }

      const data = await response.json();
      const translatedText = data[0].map(item => item[0]).join('');

      return {
        originalText: text,
        translatedText: translatedText,
        fromLang: fromLang,
        toLang: toLang,
        service: 'chrome'
      };
    } catch (error) {
      throw new Error('Chrome内置翻译失败: ' + error.message);
    }
  }

  async translateWithTencent(text, fromLang, toLang) {
    const secretId = this.apiKeys.tencent?.secretId;
    const secretKey = this.apiKeys.tencent?.secretKey;
    
    if (!secretId || !secretKey) {
      throw new Error('请先配置腾讯翻译API密钥');
    }

    const params = {
      SourceText: text,
      Source: fromLang === 'auto' ? 'auto' : fromLang,
      Target: toLang,
      ProjectId: 0
    };

    const response = await fetch('https://tmt.tencentcloudapi.com/', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
        'X-TC-Action': 'TextTranslate',
        'X-TC-Version': '2018-03-21',
        'X-TC-Region': 'ap-beijing'
      },
      body: new URLSearchParams(params)
    });

    if (!response.ok) {
      throw new Error(`腾讯翻译API错误: ${response.status}`);
    }

    const data = await response.json();
    if (data.Response && data.Response.Error) {
      throw new Error(`腾讯翻译错误: ${data.Response.Error.Message}`);
    }

    return {
      originalText: text,
      translatedText: data.Response.TargetText,
      fromLang: fromLang,
      toLang: toLang,
      service: 'tencent'
    };
  }

  async translateWithDeepL(text, fromLang, toLang) {
    const apiKey = this.apiKeys.deepl;
    if (!apiKey) {
      throw new Error('请先配置DeepL API密钥');
    }

    const response = await fetch('https://api-free.deepl.com/v2/translate', {
      method: 'POST',
      headers: {
        'Authorization': `DeepL-Auth-Key ${apiKey}`,
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      body: new URLSearchParams({
        text: text,
        source_lang: fromLang === 'auto' ? 'AUTO' : fromLang.toUpperCase(),
        target_lang: toLang.toUpperCase()
      })
    });

    if (!response.ok) {
      throw new Error(`DeepL翻译API错误: ${response.status}`);
    }

    const data = await response.json();
    if (data.translations && data.translations.length > 0) {
      return {
        originalText: text,
        translatedText: data.translations[0].text,
        fromLang: data.translations[0].detected_source_language || fromLang,
        toLang: toLang,
        service: 'deepl'
      };
    } else {
      throw new Error('DeepL翻译返回数据格式错误');
    }
  }

  async md5(message) {
    const msgBuffer = new TextEncoder().encode(message);
    const hashBuffer = await crypto.subtle.digest('MD5', msgBuffer);
    const hashArray = Array.from(new Uint8Array(hashBuffer));
    const hashHex = hashArray.map(b => b.toString(16).padStart(2, '0')).join('');
    return hashHex;
  }
}

// ======= MD5实现（blueimp-md5精简版） =======
function md5cycle(x, k) {
  var a = x[0], b = x[1], c = x[2], d = x[3];
  a = ff(a, b, c, d, k[0], 7, -680876936);
  d = ff(d, a, b, c, k[1], 12, -389564586);
  c = ff(c, d, a, b, k[2], 17, 606105819);
  b = ff(b, c, d, a, k[3], 22, -1044525330);
  a = ff(a, b, c, d, k[4], 7, -176418897);
  d = ff(d, a, b, c, k[5], 12, 1200080426);
  c = ff(c, d, a, b, k[6], 17, -1473231341);
  b = ff(b, c, d, a, k[7], 22, -45705983);
  a = ff(a, b, c, d, k[8], 7, 1770035416);
  d = ff(d, a, b, c, k[9], 12, -1958414417);
  c = ff(c, d, a, b, k[10], 17, -42063);
  b = ff(b, c, d, a, k[11], 22, -1990404162);
  a = ff(a, b, c, d, k[12], 7, 1804603682);
  d = ff(d, a, b, c, k[13], 12, -40341101);
  c = ff(c, d, a, b, k[14], 17, -1502002290);
  b = ff(b, c, d, a, k[15], 22, 1236535329);
  a = gg(a, b, c, d, k[1], 5, -165796510);
  d = gg(d, a, b, c, k[6], 9, -1069501632);
  c = gg(c, d, a, b, k[11], 14, 643717713);
  b = gg(b, c, d, a, k[0], 20, -373897302);
  a = gg(a, b, c, d, k[5], 5, -701558691);
  d = gg(d, a, b, c, k[10], 9, 38016083);
  c = gg(c, d, a, b, k[15], 14, -660478335);
  b = gg(b, c, d, a, k[4], 20, -405537848);
  a = gg(a, b, c, d, k[9], 5, 568446438);
  d = gg(d, a, b, c, k[14], 9, -1019803690);
  c = gg(c, d, a, b, k[3], 14, -187363961);
  b = gg(b, c, d, a, k[8], 20, 1163531501);
  a = gg(a, b, c, d, k[13], 5, -1444681467);
  d = gg(d, a, b, c, k[2], 9, -51403784);
  c = gg(c, d, a, b, k[7], 14, 1735328473);
  b = gg(b, c, d, a, k[12], 20, -1926607734);
  a = hh(a, b, c, d, k[5], 4, -378558);
  d = hh(d, a, b, c, k[8], 11, -2022574463);
  c = hh(c, d, a, b, k[11], 16, 1839030562);
  b = hh(b, c, d, a, k[14], 23, -35309556);
  a = hh(a, b, c, d, k[1], 4, -1530992060);
  d = hh(d, a, b, c, k[4], 11, 1272893353);
  c = hh(c, d, a, b, k[7], 16, -155497632);
  b = hh(b, c, d, a, k[10], 23, -1094730640);
  a = hh(a, b, c, d, k[13], 4, 681279174);
  d = hh(d, a, b, c, k[0], 11, -358537222);
  c = hh(c, d, a, b, k[3], 16, -722521979);
  b = hh(b, c, d, a, k[6], 23, 76029189);
  a = hh(a, b, c, d, k[9], 4, -640364487);
  d = hh(d, a, b, c, k[12], 11, -421815835);
  c = hh(c, d, a, b, k[15], 16, 530742520);
  b = hh(b, c, d, a, k[2], 23, -995338651);
  a = ii(a, b, c, d, k[0], 6, -198630844);
  d = ii(d, a, b, c, k[7], 10, 1126891415);
  c = ii(c, d, a, b, k[14], 15, -1416354905);
  b = ii(b, c, d, a, k[5], 21, -57434055);
  a = ii(a, b, c, d, k[12], 6, 1700485571);
  d = ii(d, a, b, c, k[3], 10, -1894986606);
  c = ii(c, d, a, b, k[10], 15, -1051523);
  b = ii(b, c, d, a, k[1], 21, -2054922799);
  a = ii(a, b, c, d, k[8], 6, 1873313359);
  d = ii(d, a, b, c, k[15], 10, -30611744);
  c = ii(c, d, a, b, k[6], 15, -1560198380);
  b = ii(b, c, d, a, k[13], 21, 1309151649);
  a = ii(a, b, c, d, k[4], 6, -145523070);
  d = ii(d, a, b, c, k[11], 10, -1120210379);
  c = ii(c, d, a, b, k[2], 15, 718787259);
  b = ii(b, c, d, a, k[9], 21, -343485551);
  x[0] = add32(a, x[0]);
  x[1] = add32(b, x[1]);
  x[2] = add32(c, x[2]);
  x[3] = add32(d, x[3]);
}
function cmn(q, a, b, x, s, t) {
  a = add32(add32(a, q), add32(x, t));
  return add32((a << s) | (a >>> (32 - s)), b);
}
function ff(a, b, c, d, x, s, t) {
  return cmn((b & c) | (~b & d), a, b, x, s, t);
}
function gg(a, b, c, d, x, s, t) {
  return cmn((b & d) | (c & ~d), a, b, x, s, t);
}
function hh(a, b, c, d, x, s, t) {
  return cmn(b ^ c ^ d, a, b, x, s, t);
}
function ii(a, b, c, d, x, s, t) {
  return cmn(c ^ (b | ~d), a, b, x, s, t);
}
function md51(s) {
  var n = s.length,
    state = [1732584193, -271733879, -1732584194, 271733878],
    i;
  for (i = 64; i <= n; i += 64) {
    md5cycle(state, md5blk(s.substring(i - 64, i)));
  }
  s = s.substring(i - 64);
  var tail = Array(16).fill(0);
  for (i = 0; i < s.length; i++) tail[i >> 2] |= s.charCodeAt(i) << ((i % 4) << 3);
  tail[i >> 2] |= 0x80 << ((i % 4) << 3);
  if (i > 55) {
    md5cycle(state, tail);
    tail = Array(16).fill(0);
  }
  tail[14] = n * 8;
  md5cycle(state, tail);
  return state;
}
function md5blk(s) {
  var md5blks = [], i;
  for (i = 0; i < 64; i += 4) {
    md5blks[i >> 2] =
      s.charCodeAt(i) +
      (s.charCodeAt(i + 1) << 8) +
      (s.charCodeAt(i + 2) << 16) +
      (s.charCodeAt(i + 3) << 24);
  }
  return md5blks;
}
function rhex(n) {
  var s = '', j = 0;
  for (; j < 4; j++) s += ((n >> (j * 8 + 4)) & 0x0f).toString(16) + ((n >> (j * 8)) & 0x0f).toString(16);
  return s;
}
function hex(x) {
  for (var i = 0; i < x.length; i++) x[i] = rhex(x[i]);
  return x.join('');
}
function md5(s) {
  return hex(md51(s));
}
function add32(a, b) {
  return (a + b) & 0xffffffff;
}
// 存储管理类
class StorageManager {
  static async saveHistory(translationData) {
    const history = await this.getHistory();
    const newRecord = {
      ...translationData,
      timestamp: Date.now(),
      id: crypto.randomUUID()
    };
    
    history.unshift(newRecord);
    // 只保留最近1000条记录
    if (history.length > 1000) {
      history.splice(1000);
    }
    
    await chrome.storage.local.set({ history });
    return newRecord;
  }

  static async getHistory() {
    const result = await chrome.storage.local.get('history');
    return result.history || [];
  }

  static async saveFavorite(translationData) {
    const favorites = await this.getFavorites();
    const newFavorite = {
      ...translationData,
      timestamp: Date.now(),
      id: crypto.randomUUID()
    };
    
    // 检查是否已存在相同的收藏
    const exists = favorites.some(fav => 
      fav.originalText === newFavorite.originalText && 
      fav.translatedText === newFavorite.translatedText
    );
    
    if (!exists) {
      favorites.unshift(newFavorite);
      await chrome.storage.local.set({ favorites });
    }
    
    return newFavorite;
  }

  static async getFavorites() {
    const result = await chrome.storage.local.get('favorites');
    return result.favorites || [];
  }

  static async removeFavorite(id) {
    const favorites = await this.getFavorites();
    const filtered = favorites.filter(fav => fav.id !== id);
    await chrome.storage.local.set({ favorites: filtered });
  }

  static async clearFavorites() {
    await chrome.storage.local.remove('favorites');
  }

  static async exportFavorites() {
    const favorites = await this.getFavorites();
    const csvContent = this.convertToCSV(favorites);
    return csvContent;
  }

  static async exportHistory() {
    const history = await this.getHistory();
    const csvContent = this.convertToCSV(history);
    return csvContent;
  }

  static async updateFavorite(id, newOriginal, newTranslated) {
    const favorites = await this.getFavorites();
    const idx = favorites.findIndex(fav => fav.id === id);
    if (idx !== -1) {
      favorites[idx].originalText = newOriginal;
      favorites[idx].translatedText = newTranslated;
      favorites[idx].timestamp = Date.now();
      await chrome.storage.local.set({ favorites });
    }
  }

  static convertToCSV(data) {
    const headers = ['原文', '译文', '收藏时间', '翻译服务'];
    const rows = data.map(item => [
      item.originalText,
      item.translatedText,
      new Date(item.timestamp).toLocaleString(),
      item.service
    ]);
    
    const csvContent = [headers, ...rows]
      .map(row => row.map(cell => `"${cell.replace(/"/g, '""')}"`).join(','))
      .join('\n');
    
    return csvContent;
  }
}

// 全局实例
const translationService = new TranslationService();

// 添加健康检查
let isHealthy = true;

// 定期检查扩展状态
setInterval(() => {
  try {
    if (!chrome.runtime?.id) {
      isHealthy = false;
      console.error('Extension context invalidated');
    } else {
      isHealthy = true;
    }
  } catch (error) {
    isHealthy = false;
    console.error('Health check failed:', error);
  }
}, 5000);

// 初始化右键菜单
chrome.runtime.onInstalled.addListener(() => {
  chrome.contextMenus.create({
    id: 'translateSelection',
    title: '翻译选中内容',
    contexts: ['selection']
  });
});

// 处理右键菜单点击
chrome.contextMenus.onClicked.addListener(async (info, tab) => {
  if (info.menuItemId === 'translateSelection') {
    const text = info.selectionText.trim();
    if (text) {
      const result = await translationService.translate(text);
      if (!result.error) {
        await StorageManager.saveHistory(result);
        // 发送消息到content script显示翻译结果
        chrome.tabs.sendMessage(tab.id, {
          type: 'showTranslation',
          data: result
        });
      }
    }
  }
});

// 处理来自popup和content script的消息
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  // 检查扩展是否仍然有效
  if (!chrome.runtime?.id || !isHealthy) {
    sendResponse({ error: 'Extension context invalidated' });
    return false;
  }

  (async () => {
    try {
      switch (request.type) {
        case 'translate':
          const result = await translationService.translate(request.text, request.fromLang, request.toLang);
          if (!result.error) {
            await StorageManager.saveHistory(result);
          }
          sendResponse(result);
          break;

        case 'getHistory':
          const history = await StorageManager.getHistory();
          sendResponse(history);
          break;

        case 'getFavorites':
          const favorites = await StorageManager.getFavorites();
          sendResponse(favorites);
          break;

        case 'saveFavorite':
          const savedFavorite = await StorageManager.saveFavorite(request.data);
          sendResponse(savedFavorite);
          break;

        case 'removeFavorite':
          await StorageManager.removeFavorite(request.id);
          sendResponse({ success: true });
          break;

        case 'clearFavorites':
          await StorageManager.clearFavorites();
          sendResponse({ success: true });
          break;

        case 'exportFavorites':
          const csvContent = await StorageManager.exportFavorites();
          sendResponse({ csvContent });
          break;

        case 'exportHistory':
          const csvHistory = await StorageManager.exportHistory();
          sendResponse({ csvContent: csvHistory });
          break;

        case 'getSettings':
          await translationService.loadSettings();
          sendResponse({
            currentAPI: translationService.currentAPI,
            apiKeys: translationService.apiKeys,
            autoTranslate: translationService.autoTranslate
          });
          break;

        case 'updateSettings':
          translationService.currentAPI = request.settings.currentAPI;
          translationService.apiKeys = request.settings.apiKeys;
          translationService.autoTranslate = request.settings.autoTranslate;
          await translationService.saveSettings();
          sendResponse({ success: true });
          break;

        case 'updateFavorite':
          await StorageManager.updateFavorite(request.id, request.originalText, request.translatedText);
          sendResponse({ success: true });
          break;

        default:
          sendResponse({ error: '未知的消息类型' });
      }
    } catch (error) {
      console.error('Background script error:', error);
      sendResponse({ error: error.message || 'Extension context invalidated' });
    }
  })();
  return true; // 保持消息通道开放
}); 